/*
 * @Description: EXECEL层级间匹配关系面板
 * @Author: Rfan
 * @Date: 2022-05-06 12:06:39
 * @LastEditTime: 2022-05-17 11:44:37
 */

import React, { forwardRef, Ref, useEffect, useImperativeHandle, useState } from 'react';
import { Button, Form, Select, Space } from 'antd';
import { MinusCircleOutlined, PlusOutlined, SwapOutlined } from '@ant-design/icons';
import { debounce } from 'lodash';
import { IMetadata } from '@/interfaces/metadata';

const { Option } = Select;

const LevelLink = forwardRef((props: any, ref: Ref<unknown>) => {
  const { upperLevel, lowerLevel, levelMetadata, onSubmit } = props;
  const [form] = Form.useForm();

  useImperativeHandle(ref, () => ({
    submit: () => {
      console.log(`${upperLevel?.levelName} submit`);
      form.submit();
    }
  }));

  const onFinish = (values: any) => {
    console.log('Received values of form:', values);
    onSubmit(
      values.relationList.map((item: any) => {
        return {
          highLevelField: {
            fieldName: item.upperFieldName,
            level: upperLevel.level
          },
          lowLevelField: {
            fieldName: item.lowerFieldName,
            level: lowerLevel?.level
          }
        };
      })
    );
  };

  return (
    <>
      <h4>
        {upperLevel?.levelName}与{lowerLevel?.levelName}匹配
      </h4>
      <div className="link-list">
        <Form form={form} onFinish={onFinish} autoComplete="off">
          <Form.List name="relationList">
            {(fields, { add, remove }) => (
              <>
                {fields.map((field) => (
                  <Space key={field.key} align="baseline">
                    <Form.Item
                      {...field}
                      key={`${field.key}-1`}
                      label={upperLevel?.levelName}
                      name={[field.name, 'upperFieldName']}
                    >
                      <Select style={{ width: 130 }}>
                        {(levelMetadata[upperLevel?.level] || []).map((item: IMetadata) => (
                          <Option key={item.field_name} value={item.field_name}>
                            {item.field_desc}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                    <SwapOutlined />
                    <Form.Item
                      {...field}
                      key={`${field.key}-2`}
                      label={lowerLevel?.levelName}
                      name={[field.name, 'lowerFieldName']}
                    >
                      <Select style={{ width: 130 }}>
                        {(levelMetadata[lowerLevel?.level] || []).map((item: IMetadata) => (
                          <Option key={item.field_name} value={item.field_name}>
                            {item.field_desc}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(field.name)} />
                  </Space>
                ))}
                <Form.Item>
                  <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    增加
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form>
      </div>
    </>
  );
});

const ExcelLevel = (props: any, ref: Ref<unknown>) => {
  const { levelList, levelMetadata } = props;
  const [infoList, setInfoList] = useState([]);
  const [levelRelationList, setLevelRelationList] = useState<any[]>([]);

  useImperativeHandle(ref, () => ({
    submit: () => {
      console.log('child submit');
      infoList.forEach((item: any) => {
        item.ref.current.submit();
      });
    }
  }));

  useEffect(() => {
    if (levelList && levelList.length > 0) {
      setInfoList(
        levelList
          .map((level: any, idx: number, arr: any[]) => {
            const next = arr[idx + 1];
            // if (next) {
            return {
              key: level.level,
              upperLevel: level,
              lowerLevel: next,
              ref: { current: {} }
            };
            // }
            // return undefined;
          })
          .filter((item: any) => item)
      );
    }
  }, [levelList]);

  const submitForms = (vals: any) => {
    console.log('vals', vals);
    setTimeout(() => {
      setLevelRelationList((state) => [...state, vals]);
      editLevelRelations();
    }, 10);
  };

  const editLevelRelations = debounce(() => {
    console.log(levelRelationList.length);
  }, 200);

  return (
    <div>
      {infoList.map((item) => (
        <LevelLink levelMetadata={levelMetadata} {...item} onSubmit={submitForms} />
      ))}
    </div>
  );
};

export default forwardRef(ExcelLevel);
